package com.tang.jvm;

import java.io.FileInputStream;

/**
 * @author Tang
 * @classname MyClassloader
 * @description [  ]
 * @date 2021/6/1 21:43
 */
public class MyClassloader extends ClassLoader {

    private String classPathName;

    public MyClassloader(String className) {
        this.classPathName = className;
    }

    @Override
    public Class findClass(String name) {
        byte[] b = new byte[0];
        try {
            b = loadClassData(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(classPathName);
        byte[] bt = new byte[fileInputStream.available()];
        fileInputStream.read(bt);
        fileInputStream.close();
        return bt;
    }

    public static void main(String[] args) throws Exception {
        MyClassloader myClassloader = new MyClassloader("C:\\Users\\ASUS\\Desktop\\com\\tang\\jvm\\User.class");
        // loadClass 调用 findClass
        Class<?> aClass1 = myClassloader.loadClass("com.tang.jvm.User");
        System.out.println(aClass1.getClassLoader());
        aClass1.getMethod("user")
                .invoke(aClass1.newInstance(), null);

        MyClassloader myClassloader1 = new MyClassloader("C:\\Users\\ASUS\\Desktop\\com\\tang\\jvm\\test\\User.class");
        // loadClass 调用 findClass
        Class<?> aClass2 = myClassloader1.loadClass("com.tang.jvm.test.User");
        System.out.println(aClass2.getClassLoader());
        aClass1.getMethod("user")
                .invoke(aClass1.newInstance(), null);
    }

}